let currentWordIndex;
let audio = new Audio();
let wordDetails;

function playWord() {
    audio.play();
}


function disableButtons() {
    // Example of disabling buttons
    document.querySelector('button[onclick="nextWord()"]').disabled = true;
    document.querySelector('button[onclick="submitWord()"]').disabled = true;
    document.querySelector('button[onclick="showWord()"]').disabled = true;
    document.querySelector('button[onclick="showPronunciation()"]').disabled = true;
    document.querySelector('button[onclick="showExplanation()"]').disabled = true;

    // Optionally, you might also want to disable the input field
    document.getElementById('userInput').disabled = true;
}
function enableButtons() {
    document.querySelector('button[onclick="nextWord()"]').disabled = false;
    document.querySelector('button[onclick="submitWord()"]').disabled = false;
    document.querySelector('button[onclick="showWord()"]').disabled = false;
    document.querySelector('button[onclick="showPronunciation()"]').disabled = false;
    document.querySelector('button[onclick="showExplanation()"]').disabled = false;

    // Optionally, re-enable the input field
    document.getElementById('userInput').disabled = false;
}



function fetchWord() {
    fetch('/get_word')
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                // If the response contains a message (like "No more words available")
                document.getElementById('result').innerText = data.message;
                disableButtons(); // Disable relevant buttons
            } else {
                // Normal operation: set the word index and audio source
                currentWordIndex = data.index;
                audio.src = data.audio_file;
                document.getElementById('details').innerText = '';
                playWord(); // Play the audio after fetching the word
            }
        })
        .catch(error => {
            console.error('Error fetching word:', error);
            document.getElementById('result').innerText = 'Error fetching new word';
        });
}


function submitWord() {
    const userInput = document.getElementById('userInput').value;
    fetch('/check_word', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({index: currentWordIndex, user_input: userInput})
    })
        .then(response => response.json())
        .then(data => {
            document.getElementById('result').innerText = data.result;
        });
}

let counter = 0; // Initialize counter

function nextWord() {
    document.getElementById('userInput').value = '';
    document.getElementById('result').innerText = '';
    document.getElementById('details').innerText = '';
    fetchWord();
    incrementCounter(); // Increment the counter when fetching the next word
}

function incrementCounter() {
    counter++;
    document.getElementById('counter').innerText = counter;
}


function resetCounter() {
    counter = 0;
    document.getElementById('counter').innerText = counter;
    fetch('/reset', {method: 'POST'})
        .then(response => response.json())
        .then(data => {
            console.log(data.message); // Log the response message
            // Refresh the page
            window.location.reload();
        })
        .catch(error => {
            console.error('Error resetting index:', error);
            // Optionally, refresh even if there's an error
            window.location.reload();
        });
}



function showDetails(callback) {
    fetch(`/get_details?index=${currentWordIndex}`)
        .then(response => response.json())
        .then(data => callback(data.details));
}

function showWord() {
    showDetails(details => {
        let detailsHtml = `<strong>Word:</strong> ${details[0]}<br>`;
        detailsHtml += `<strong>Pronunciation:</strong> ${details[1]}<br>`;
        detailsHtml += `<strong>Explanation:</strong> ${details[2]}`;
        document.getElementById('details').innerHTML = detailsHtml;
    });
}

function showPronunciation() {
    showDetails(details => {
        document.getElementById('details').innerHTML = `<strong>Pronunciation:</strong> ${details[1]}`;
    });
}

function showExplanation() {
    showDetails(details => {
        document.getElementById('details').innerHTML = `<strong>Explanation:</strong> ${details[2]}`;
    });
}

function clearContent() {
    document.getElementById('userInput').value = ''; // Clear the input field
    document.getElementById('result').innerText = ''; // Clear the result message
    document.getElementById('details').innerText = ''; // Clear details
}

function checkEnter(event) {
    if (event.key === 'Enter') {
        submitWord(); // Call the submitWord function if Enter is pressed
    }
}

document.addEventListener('keydown', function(event) {
    // Check if the 'Command' key (or 'Meta' key in some browsers) is pressed along with the 'N' key
    if (event.ctrlKey && event.key === 'n') {
        nextWord(); // Call the nextWord function if Command + N is pressed
        event.preventDefault(); // Prevent the default behavior (e.g., opening a new browser window)
    }

    // Check if 'Ctrl' key is pressed along with the 'p' key
    if (event.ctrlKey && event.key === 'p') {
        playWord(); // Call the play function if Ctrl + p is pressed
        event.preventDefault(); // Prevent the default behavior
    }

    if (event.ctrlKey && event.key === 's') {
        showWord(); 
        event.preventDefault(); // Prevent the default behavior
    }

    // Check if 'Ctrl' key is pressed along with the 'r' key
    if (event.ctrlKey && event.key === 'r') {
        showPronunciation(); // Call the showPronunciation function if Ctrl + r is pressed
        event.preventDefault(); // Prevent the default behavior
    }

    // Check if 'Ctrl' key is pressed along with the 'E' key
    if (event.ctrlKey && event.key === 'e') {
        showExplanation(); // Call the showExplanation function if Ctrl + E is pressed
        event.preventDefault(); // Prevent the default behavior
    }
});

fetchWord(); // fetch the first word on page load and play the audio
